﻿using B.S.Data.MES.API.Applications.Management.SteamApplication.Command.FactoryCommand;
using B.S.Domain.Accounts;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;

namespace B.S.Data.MES.API.Applications.Management.SteamApplication.CommandHandler.FactoryCommandHandler
{
    public class FactoryQueryCommandHandler : IRequestHandler<FactoryQueryCommand, APIRequst<APIPageing<List<FactoryClass>>>>
    {
        public FactoryQueryCommandHandler(IBaseRepository<FactoryClass> factoryRepository)
        {
            FactoryRepository = factoryRepository;
        }

        public IBaseRepository<FactoryClass> FactoryRepository { get; }

        public async Task<APIRequst<APIPageing<List<FactoryClass>>>> Handle(FactoryQueryCommand request, CancellationToken cancellationToken)
        {
            var path = FactoryRepository.GetAll();
            if(!string.IsNullOrEmpty(request.VendorCord))
            {
                path = path.Where(a => a.VendorCord.Contains(request.VendorCord));
            }
            if(!string.IsNullOrEmpty(request.FactoryName))
            {
                path = path.Where(a => a.FactoryName.Contains(request.FactoryName));
            }
            if(!string.IsNullOrEmpty(request.CreateName))
            {
                path = path.Where(a => a.CreateName.Contains(request.CreateName));
            }

            var totalCount = path.Count();
            var pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            var listDto = path.OrderBy(a => a.FactoryId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return new APIRequst<APIPageing<List<FactoryClass>>>
            {
                Code = RequstCode.成功,
                Msg = "查询成功",
                Data = new APIPageing<List<FactoryClass>>
                {
                    Total = pageCount,
                    TotalCount = totalCount,
                    Data = listDto
                }
            };
        }
    }
}
